package site.longkui.scloudproviderhystrix.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {


    //第一个测试
    @GetMapping("/getNewUser1")
    @HystrixCommand(fallbackMethod = "myError1")
    public String getUser1() {
        return "I`m provider hystrix1 ,return user1";
    }

    //用于处理服务调用失败时的情况，对应上面的fallbackMethod = "myError1"
    public String myError1(){
        return "default error111111";
    }

    //第二个测试
    @GetMapping("/getNewUser2")
    @HystrixCommand(fallbackMethod = "myError2",commandProperties = {
            //2秒钟以内就是正常的业务逻辑,超过两秒则认为服务调用失败
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
    })
    public String getUser2() {
        try {
            //睡眠3秒，这个服务因为上面2秒的限制就会失败
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "I`m provider hystrix1 ,return user2";
    }

    //用于处理服务调用失败时的情况，对应上面的fallbackMethod = "myError2"
    public String myError2(){
        return "default error22222";
    }



    //第三个测试，开启断路器
    @GetMapping("/getNewUser3/{id}")
    @HystrixCommand(fallbackMethod = "myError3",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),		// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),	// 请求次数阈值
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), 	// 时间窗口期 10秒
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),		// 错误百分比阀值：失败率达到多少后跳闸
    })
    public String getUser3(@PathVariable("id") Integer id){
        long timestamp = System.currentTimeMillis();
        if(id>10){
            System.out.println("exception~"+timestamp);
            throw new RuntimeException("exception~"+timestamp);
        }
        //正常逻辑
        System.out.println("I`m provider hystrix1 ,return user3~"+timestamp);
        return "I`m provider hystrix1 ,return user3~"+timestamp;
    }

    //用于处理服务调用失败时的情况，对应上面的fallbackMethod = "myError2"
    //注意，参数要一致
    public String myError3(Integer id){
        long timestamp = System.currentTimeMillis();
        System.out.println("default error33333~"+timestamp);
        return "default error33333~"+timestamp;
    }

}
